import { addOutputLine } from './LogUtil'
import { useGitStore } from '../store/GitStore'

// 执行 git 命令
const runCommand = (currentDirectory, command) => {
  let commandStr
  if (!currentDirectory.value) {
    addOutputLine('请先选择工作目录', 'error')
    return
  }
  // 处理带参数的命令
  if (typeof command === 'string') {
    commandStr = command
  }
  // 处理对象形式的复杂命令
  else if (typeof command === 'object') {
    commandStr = command.command
    if (command.confirm && !confirm(command.message)) {
      return
    }
  } else {
    // 弹出错误提示
    addOutputLine('请输入正确的命令', 'error')
  }
  executeCommand(currentDirectory, commandStr)
}

// 执行 Git 命令
const executeCommand = async (currentDirectory, command) => {
  const fullCommand = command.value.trim()
  if (!fullCommand || !currentDirectory) return

  const gitStore = useGitStore()
  gitStore.setExecuting(true)

  const [cmd, ...args] = fullCommand.split(/\s+/).filter((arg) => arg)

  // 显示命令
  addOutputLine(fullCommand, 'command')

  try {
    // 执行命令
    await window.electronAPI.executeGit(cmd, args, currentDirectory)
  } catch (error) {
    addOutputLine(`命令执行失败: ${error.errorOutput || error.error || '未知错误'}`, 'stderr')
  } finally {
    gitStore.setExecuting(false)
  }
}
